<?php

/**
 * Interfejs dla encji w bazie danych - reprezentacja jednej krotki.
 *
 * @author Rafał Cupał
 * @author Przemysław Furmańczyk
 */
abstract class Entity {
    protected $dataBase;
    protected $tableName;
    
    protected $id;
    
    public function __construct($dataBase, $tableName) {
        $this->id = 0;
        $this->dataBase = $dataBase;
        $this->tableName = $tableName;
    }
    
    public function getId() {
        return $this->id;
    }
    
    public function find($attributes, $columns) {
        if (!is_array($attributes) or count($attributes) == 0 or
            !is_array($columns) or count($columns) == 0) {
            return 0;
        }
        
        $columns[] = 'id';
        $columns = array_unique($columns);
        
        $command = 'SELECT ' . implode(', ', $columns) . 
                ' FROM ' . $this->tableName;
        
        //Warunki
        $command .= " WHERE ";
        $first_condition = true;
        foreach ($attributes as $column => $value) {
            if ($first_condition) {
                $first_condition = false;
            }
            else {
                $command .= ' AND ';
            }
            $command .= $column . ' = ' . $value;
        }
        
        $numRows = 0;
        
        $statement = $this->dataBase->query($command);
        while ($row = $statement->fetch()) {
            if ($numRows == 0) {
                $this->load($row);
            }
            $numRows++;
        }
        $statement->closeCursor();
        
        return $numRows;
    }
	
	public function remove() {
		if ($this->id > 0) {
			$this->dataBase->exec('DELETE FROM ' . $this->tableName . 
				' WHERE id = ' . $this->id);
			$this->id = 0;
		}
	}
    
    protected function getRowData($rowData, &$variable, $columnName) {
        if (isset($rowData[$columnName])) {
            $variable = $rowData[$columnName];
        }
        else {
            $variable = NULL;
        }
    }
    
    protected function setRowData(&$rowData, $variable, $columnName) {
        if (isset($variable)) {
            $rowData[$columnName] = $variable;
        }
    }
    
    abstract public function load($rowData);
    abstract public function save();
}
